package com.haixee.parkdemo.auth.controller;

import com.haixee.parkdemo.auth.entity.request.RoleFieldRequest;
import com.haixee.parkdemo.auth.entity.request.RoleRequest;
import com.haixee.parkdemo.auth.service.RoleScopeService;
import com.haixee.parkdemo.auth.service.RoleService;
import com.haixee.parkdemo.auth.service.ViewService;
import com.haixee.parkdemo.auth.utils.TenantUtil;
import com.haixee.parkdemo.common.response.ResResult;
import com.haixee.parkdemo.common.response.ResUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleScopeService roleScopeService;

    @Autowired
    private ViewService viewService;

    @PostMapping("/add")
    public ResResult addRole(@RequestBody RoleRequest request) {

        roleService.addRole(request.getRoleName(), request.getTenantId());
        return ResUtil.success();
    }

    @GetMapping("/all")
    public ResResult getAll(Integer tenantId) {
        tenantId = TenantUtil.check(tenantId);
        return ResUtil.success(roleService.selectAll(tenantId));
    }

    @GetMapping("/acl")
    public ResResult getAcl(Integer roleId) {
        return ResUtil.success(roleService.getAclList(roleId));
    }

    @PostMapping("/acl")
    public ResResult setAcl(@RequestBody RoleRequest request) {
        roleService.setAcl(request.getRoleId(), request.getAclId());
        return ResUtil.success();
    }

    @PostMapping("/scope")
    public ResResult setScope(@RequestBody RoleRequest request) {

        roleScopeService.setRoleScope(request.getRoleId(), request.getScope());

        return ResUtil.success();
    }

    @GetMapping("/scope")
    public ResResult getScope(Integer roleId) {

        Byte roleScope = roleScopeService.getRoleScope(roleId);
        Map<String, Byte> result = new HashMap<>();
        result.put("scope", roleScope);

        return ResUtil.success(result);
    }


    @PostMapping("/field")
    public ResResult setField(@RequestBody RoleFieldRequest roleField) {

        viewService.updateRoleView(roleField.getRoleId(), roleField.getFieldId(), roleField.getAclType(), roleField.getUse());

        return ResUtil.success();
    }

    @GetMapping ("/field")
    public ResResult getField(Integer roleId) {

        return ResUtil.success(viewService.getRoleFields(roleId));
    }
}
